package com.jinbai.servlet.track;

import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jinbai.service.TrackService;
import com.jinbai.util.Log;
import com.jinbai.view_object.ListTrackVO;
import com.jinbai.view_object.StudioTrackListView;
import com.jinbai.view_object.UserVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/studio/track/list.json")
public class ListJsonServlet extends HttpServlet {
    private final TrackService trackService = new TrackService();
    private final ObjectMapper objectMapper = new ObjectMapper();

    public ListJsonServlet() {
        objectMapper.setDefaultPrettyPrinter(new DefaultPrettyPrinter()); // 美化json使其带有空格和换行
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Log.println("访问 GET /studio/track/list.json");

        int page;
        String pageString = req.getParameter("page");
        if (pageString == null || pageString.trim().isEmpty()) {
            Log.println("请求参数中未携带页码信息，默认成第一页");
            page = 1;
        } else {
            pageString = pageString.trim();
            try {
                page = Integer.parseInt(pageString);
                if (page < 0) {
                    Log.println("page小于0，默认成第一页");
                    page = 1;
                }
            } catch (NumberFormatException e) {
                Log.println("传入页码格式不对不是数字，默认为第一页");
                page = 1;
            }
        }

        StudioTrackListView studioTrackListView = new StudioTrackListView();
        UserVO currentUser = null;
        final HttpSession session = req.getSession(false);
        if (session != null) {
            currentUser = (UserVO) session.getAttribute("currentUser");
        }
        if (currentUser == null) {
            Log.println("用户未登录");
            resp.sendRedirect("/studio/user/login.html");
            return;
        }

        Log.println(currentUser + "用户已经登录");
        studioTrackListView.setCurrentUser(currentUser);

        // 目标：得到当前用户的音频的列表List<ListTrackVO>对象
        studioTrackListView = trackService.listOfUser(currentUser, page);
//        studioTrackListView.setTrackVOList(trackVOList);
        Log.println("准备json序列化的对象是： " + studioTrackListView);

        String json = objectMapper.writeValueAsString(studioTrackListView);
        Log.println("json序列化后的结果为：" + json);

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        final PrintWriter writer = resp.getWriter();
        Log.println("将json写入response中");
        writer.println(json);
    }
}
